package com.heaven1949.tmall.common.web.config;

import com.heaven1949.tmall.common.core.constants.CommonConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * FeignConfig
 *
 * @author zhangjian
 * @date 2023-03-10 17:09:18
 */
@Slf4j
@Configuration
public class FeignConfig implements RequestInterceptor {

    /**
     * 拦截feign进行拦截，并在请求头添加，需要添加的header参数
     *
     * @param template
     */
    @Override
    public void apply(RequestTemplate template) {
        try {
            // 获取请求对象
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (Objects.nonNull(servletRequestAttributes)) {
                HttpServletRequest request = servletRequestAttributes.getRequest();
                // 获取当前请求的header，获取到jwt令牌
                if (Objects.nonNull(request.getHeader(CommonConstant.AUTHORIZATION_KEY))) {
                    template.header(CommonConstant.AUTHORIZATION_KEY, request.getHeader(CommonConstant.REQUEST_KEY));
                }
                String traceId = MDC.get(CommonConstant.REQUEST_KEY);
                if (StringUtils.isNotBlank(traceId)) {
                    template.header(CommonConstant.REQUEST_KEY, traceId);
                }
            }
        } catch (Exception ex) {
            log.error("FeignConfig apply error：", ex);
        }
    }

}